package com.qiudao.basestudy.dao.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiudao.basestudy.bo.App;
import com.qiudao.basestudy.dao.IAppDao;
import com.qiudao.basestudy.mapper.AppMapper;
import com.qiudao.basestudy.util.DataConverUtil;
import com.qiudao.basestudy.util.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description: AppDao 实现
 * @author: gdc
 * @date: 2020/3/21
 * @version 1.0
 */
@Repository
public class AppDaoImpl implements IAppDao {

    @Resource
    private AppMapper appMapper;

    @Override
    public App get(Long id) {
        return appMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(App app) {
        return appMapper.insertSelective(app);
    }

    @Override
    public int delete(Long id) {
        return appMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo findAppByQuery(App app, Integer pageNum, Integer pageSize) {
        List<App> apps = getAppList(app, pageNum, pageSize);
        return DataConverUtil.pageInfoConver(App.class, apps);
    }

    @Override
    public List<App> getAppList(App app) {
        List<App> apps = getAppList(app, null, null);
        return DataConverUtil.listTypeConver(App.class, apps);
    }

    private List<App> getAppList(App app, Integer pageNum, Integer pageSize) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("name", StringUtils.isEmpty(app.getName()) ? null : app.getName());
        map.put("code", StringUtils.isEmpty(app.getCode()) ? null : app.getCode());
        map.put("isValid", app.getIsValid());
        if (Objects.nonNull(pageSize) && Objects.nonNull(pageNum)) {
            // 分页查询 pageNum 页码， pageSize 显示条数
            PageHelper.startPage(PageUtils.getPageNum(pageNum), PageUtils.getPageSize(pageSize));
        }
        return appMapper.findListByQuery(map);
    }
}
